package com.zgg.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

/**
 * Created by Administrator on 2017/8/15 0015.
 */
public class PropertyUtils {
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);

    //项目内配置集合
    private static Properties props;
    private static Set<String> fileSet;

    synchronized static private void loadProps(String fileName) {
        if (props == null) {
            props = new Properties();
        }
        if (fileSet == null){
            fileSet = new HashSet<>();
        }
        if (!fileSet.contains(fileName)) {
            fileSet.add(fileName);

            InputStream in = null;
            logger.info("开始加载properties文件内容.......");
            Properties tempProps = new Properties();
            try {
//　　　　　　　<!--第一种，通过类加载器进行获取properties文件流-->
                in = PropertyUtils.class.getClassLoader().getResourceAsStream(fileName);
                //将配置文件内容加载到临时内容里。
                tempProps.load(in);

                Iterator keys = tempProps.keySet().iterator();
                while (keys.hasNext()) {
                    String key = String.valueOf(keys.next());
                    if (!props.containsKey(key)) {
                        props.put(key, tempProps.getProperty(key));
                    }
                }
            } catch (FileNotFoundException e) {
                logger.error(fileName + "文件未找到");
            } catch (IOException e) {
                logger.error("出现IOException");
            } finally {
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("jdbc.properties文件流关闭出现异常");
                }
            }
            logger.info("加载properties文件内容完成...........");
            logger.info("properties文件内容：" + props);
        }
    }

    public static String getProperty(String fileName, String key) {
        loadProps(fileName);
        return props.getProperty(key);
    }

    public static String getProperty(String fileName, String key, String defaultValue) {
        loadProps(fileName);
        return props.getProperty(key, defaultValue);
    }
    public static Object setProperty(String fileName,String key,String value) {
        loadProps(fileName);
        return props.setProperty(key,value);
    }

}
